package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.CarBean;
import com.project.bean.OrderBean;
import com.project.mapper.ICarMapper;
import com.project.mapper.IOrderMapper;
import com.project.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private IOrderMapper orderMapper;
    @Autowired
    private ICarMapper carMapper;
    @Override
    public IPage<OrderBean> findAllByID(Integer id, int pageNo) {
        QueryWrapper<OrderBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId",id);
        return orderMapper.selectPage(new Page<OrderBean>(pageNo,PAGESIZE),qw);
    }

    @Override
    public OrderBean findById(int id) {
        return orderMapper.findById(id);
    }

    @Override
    public void add(OrderBean orderBean, Integer userId) {
        orderBean.setUserId(userId);
        //添加订单
        orderMapper.insert(orderBean);
        //得到该用户的购物车信息
        QueryWrapper<CarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId",userId);
        List<CarBean>carBeanList = carMapper.selectList(qw);

        //添加订单的明细
        orderMapper.addOrderInfo(orderBean.getId(),carBeanList);

        //清空该用户的购物信息
        carMapper.delete(qw);
    }

    @Override
    public IPage<OrderBean> findByItem(String status, LocalDate startDate, LocalDate endDate, int pageNO) {
        QueryWrapper<OrderBean> qw = new QueryWrapper<>();
        if (status != null && status.length()!=0){
            qw.eq("o_status",status);
        }
        if (startDate != null){
            qw.ge("o_createDate",startDate);
        }
        if (endDate != null){
            qw.le("o_createDate",endDate);
        }

        return orderMapper.selectPage(new Page<OrderBean>(pageNO,PAGESIZE),qw);
    }

    @Override
    public void updateStatus(int orderId, String status) {
        OrderBean orderBean =new OrderBean();
        orderBean.setStatus(status);
        orderBean.setId(orderId);
        orderMapper.updateById(orderBean);
    }

    @Override
    public List<OrderBean> findBySend() {
        QueryWrapper<OrderBean> qw = new QueryWrapper<>();
        qw.eq("o_status","发货中");
        return orderMapper.selectList(qw);

    }
}
